package com.jingtai.platform.service.shop.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jingtai.common.enums.*;
import com.jingtai.common.template.ResultMapInfo;
import com.jingtai.common.utils.random.TokenUtil;
import com.jingtai.core.entity.shop.*;
import com.jingtai.core.entity.supply.SupplyGoods;
import com.jingtai.core.entity.supply.SupplyGoodsDetail;
import com.jingtai.core.entity.supply.SupplyGoodsWarehouse;
import com.jingtai.core.mapper.shop.MerchantsGoodsMapper;
import com.jingtai.platform.service.shop.*;
import com.jingtai.platform.service.supply.SupplyGoodsDetailService;
import com.jingtai.platform.service.supply.SupplyGoodsService;
import com.jingtai.platform.service.supply.SupplyGoodsWarehouseService;
import com.jingtai.platform.util.JsonUtils;
import com.jingtai.platform.util.ResultUtil;
import com.jingtai.platform.util.SkuArrAy;
import com.jingtai.platform.util.UrlToMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


/**
 * 商户商品表 impl
 *
 * @author sunlaiqian
 * @date 2020-12-02 18:31:32
 */
@Service
public class MerchantsGoodsServiceImpl extends ServiceImpl<MerchantsGoodsMapper, MerchantsGoods> implements MerchantsGoodsService {

    @Autowired
    private MerchantsGoodsService merchantsGoodsService;
    @Autowired
    private MerchantsGoodsDetailService merchantsGoodsDetailService;
    @Autowired
    private MerchantsGoodsWarehouseService merchantsGoodsWarehouseService;
    @Autowired
    private GoodsSpecificationsCustomService goodsSpecificationsCustomService;
    @Autowired
    private SupplyGoodsService supplyGoodsService;
    @Autowired
    private SupplyGoodsDetailService supplyGoodsDetailService;
    @Autowired
    private SupplyGoodsWarehouseService supplyGoodsWarehouseService;
    @Autowired
    private GoodsSpecificationsService goodsSpecificationsService;

    @Override
    public ResultUtil MerchantsGoodslist(Integer page, Integer limit, String conditions){
        QueryWrapper<MerchantsGoods> wrapper = new QueryWrapper<>();
        Map<String, String> map = UrlToMap.paramToMap(conditions);
        for(Map.Entry<String, String> entry : map.entrySet()){
            wrapper.like(entry.getKey(), entry.getValue());
        }
        wrapper.eq("delete_flag", DeleteFlagEnum.NOT_DELETE.getCode());
        return new ResultUtil(ResultMapInfo.GETSUCCESS,merchantsGoodsService.page(new Page<>(page,limit),wrapper));
    }

    @Override
    public ResultUtil addMerchantsGoods(MerchantsGoods merchantsGoods) {
        String goodsCode = TokenUtil.generateUUID();
        merchantsGoods.setGoodsCode(goodsCode);
        boolean save = merchantsGoodsService.save(merchantsGoods);
        return save ? new ResultUtil(ResultMapInfo.ADDSUCCESS,merchantsGoods):new ResultUtil(ResultMapInfo.ADDFAIL);
    }

    @Override
    public ResultUtil getMerchantsGoodsById(Long id) {
        MerchantsGoods merchantsGoods = merchantsGoodsService.getById(id);
        return merchantsGoods == null ?  new ResultUtil(ResultMapInfo.GETFAIL) : new ResultUtil(ResultMapInfo.GETSUCCESS,merchantsGoods);
    }

    @Override
    public ResultUtil delMerchantsGoodsById(Long id) {
        MerchantsGoods merchantsGoods = new MerchantsGoods();
        merchantsGoods.setId(id);
        merchantsGoods.setDeleteFlag(DeleteFlagEnum.DELETE.getCode());
        boolean delState = merchantsGoodsService.updateById(merchantsGoods);
        return delState ?  new ResultUtil(ResultMapInfo.DELETESUCCESS) : new ResultUtil(ResultMapInfo.DELETEFAIL);
    }

    @Override
    public ResultUtil addMerchantsGoodsByGoodsCode(String goodsCode,Long merchantsId) {
        //判断有没有添加过
        List<MerchantsGoods> list1 = merchantsGoodsService.list(Wrappers.lambdaQuery(MerchantsGoods.class).eq(MerchantsGoods::getGoodsCode, goodsCode));
        if (list1.size() > 0){
            return new ResultUtil(ResultMapInfo.NUMBERDUPLICATION);
        }
        //1.根据商品编号查询商品
        SupplyGoods supplyGoods = supplyGoodsService.getOne(Wrappers.lambdaQuery(SupplyGoods.class).eq(SupplyGoods::getGoodsCode, goodsCode));
        if (supplyGoods.getApplyState() == ApplyStateEnum.APPLY_DAI_CHU_LI.getCode() ||supplyGoods.getApplyState() == ApplyStateEnum.APPLY_WEI_TONG_GUO.getCode() ||supplyGoods.getApplyState() == ApplyStateEnum.APPLY_YI_CHE_XIAO.getCode()){
            return new ResultUtil(ResultMapInfo.NO_RECORD_OR_ERROR_STATUS);
        }
        //2.根据商品编号查询商品详情
        SupplyGoodsDetail supplyGoodsDetail = supplyGoodsDetailService.getOne(Wrappers.lambdaQuery(SupplyGoodsDetail.class).eq(SupplyGoodsDetail::getGoodsCode, goodsCode));
        //3.根据商品编号查询商品属性
        List<SupplyGoodsWarehouse> list = supplyGoodsWarehouseService.list(Wrappers.lambdaQuery(SupplyGoodsWarehouse.class).eq(SupplyGoodsWarehouse::getGoodsCode, goodsCode));
        //4.转换商品
        MerchantsGoods merchantsGoods = JsonUtils.string2Obj(JSON.toJSONString(supplyGoods),MerchantsGoods.class);
        merchantsGoods.setMerchantsId(merchantsId).setGoodsPrice(supplyGoods.getUnitPrice()).setGoodsState(GoodsStatusEnum.REMOVE_FROM_LIST.getStatus()).setGoodsSource(SourceTypeEnum.SUPPLIER.getStatus()).setStoreId(null).setId(null);
        boolean save = merchantsGoodsService.save(merchantsGoods);
        if (!save){
            return new ResultUtil(ResultMapInfo.ADDFAIL);
        }
        //5.转换 商品详情
        MerchantsGoodsDetail merchantsGoodsDetail = JsonUtils.string2Obj(JSON.toJSONString(supplyGoodsDetail),MerchantsGoodsDetail.class);
        merchantsGoodsDetail.setId(null);
        boolean save1 = merchantsGoodsDetailService.save(merchantsGoodsDetail);
        if (!save1){
            return new ResultUtil(ResultMapInfo.ADDFAIL);
        }
        //6.转换商品属性
        List<MerchantsGoodsWarehouse> merchantsGoodsWarehouses = new ArrayList<>();
        for (SupplyGoodsWarehouse supplyGoodsWarehouse : list){
            MerchantsGoodsWarehouse merchantsGoodsWarehouse = JsonUtils.string2Obj(JSON.toJSONString(supplyGoodsWarehouse),MerchantsGoodsWarehouse.class);
            merchantsGoodsWarehouse.setId(null);
            merchantsGoodsWarehouse.setMerchantsId(merchantsId);
            merchantsGoodsWarehouses.add(merchantsGoodsWarehouse);
        }
        boolean save2 = merchantsGoodsWarehouseService.saveBatch(merchantsGoodsWarehouses);
        return save2 ? new ResultUtil(ResultMapInfo.ADDSUCCESS,merchantsGoods):new ResultUtil(ResultMapInfo.ADDFAIL);
    }

    @Override
    public ResultUtil refreshGoodsListByGoodsCode(String goodsCode) {
        //1.根据商品列表查询商品
        MerchantsGoods one = merchantsGoodsService.getOne(Wrappers.lambdaQuery(MerchantsGoods.class).eq(MerchantsGoods::getGoodsCode, goodsCode).eq(MerchantsGoods::getDeleteFlag,DeleteFlagEnum.NOT_DELETE.getCode()));
        //查询商品规格
        String json = "";
        List<JSONObject> jsonObjectList = (List<JSONObject>)goodsSpecificationsService.selectGoodsSpecificationsByGoodsCode(goodsCode, 1).getData();
        for(JSONObject jsonObject : jsonObjectList){
            if (jsonObject.getInteger("type") == 1){
                json += jsonObject.getString("specificationsName") + ":" + 0;
            }else {
                json += jsonObject.getString("specificationsName") + ":" + "请填写" + jsonObject.getString("specificationsName");
            }
        }
        Map<String,GoodsSpecificationsCustom> map = new HashMap<>();
        //2.根据商品编码查询一级自定义规格
        List<GoodsSpecificationsCustom> listOfOne = goodsSpecificationsCustomService.list(Wrappers.lambdaQuery(GoodsSpecificationsCustom.class).eq(GoodsSpecificationsCustom::getGoodsCode, goodsCode).eq(GoodsSpecificationsCustom::getLevel, LevelEnum.ONELEVEL.getValue()).eq(GoodsSpecificationsCustom::getEnableState, EnableStatusEnum.NORMAL.getValue()).eq(GoodsSpecificationsCustom::getDeleteFlag, DeleteFlagEnum.NOT_DELETE.getCode()));
        //3.根据一级自定义规格 查询二级自定义规格
        List<List<String>> lists = new ArrayList<>();
        for (GoodsSpecificationsCustom goodsSpecificationsCustom : listOfOne){
            map.put(goodsSpecificationsCustom.getId().toString(),goodsSpecificationsCustom);
            List<GoodsSpecificationsCustom> listOfTwo = goodsSpecificationsCustomService.list(Wrappers.lambdaQuery(GoodsSpecificationsCustom.class).eq(GoodsSpecificationsCustom::getGoodsCode, goodsCode).eq(GoodsSpecificationsCustom::getLevelOfOne,goodsSpecificationsCustom.getId()).eq(GoodsSpecificationsCustom::getLevel, LevelEnum.TWOLEVEL.getValue()).eq(GoodsSpecificationsCustom::getEnableState, EnableStatusEnum.NORMAL.getValue()).eq(GoodsSpecificationsCustom::getDeleteFlag, DeleteFlagEnum.NOT_DELETE.getCode()));
            List<String> stringList = new ArrayList<>();
            for (GoodsSpecificationsCustom goodsSpecificationsCustom1 : listOfTwo){
                map.put(goodsSpecificationsCustom1.getId().toString(),goodsSpecificationsCustom1);
                stringList.add(goodsSpecificationsCustom1.getId().toString());
            }
            lists.add(stringList);
        }
        String[] conversion = SkuArrAy.conversion(lists);
        System.out.println(conversion);
        //删除原来的商品属性
        List<MerchantsGoodsWarehouse> list1 = merchantsGoodsWarehouseService.list(Wrappers.lambdaQuery(MerchantsGoodsWarehouse.class).eq(MerchantsGoodsWarehouse::getGoodsCode, goodsCode));
        if(list1.size() > 0){
            boolean remove = merchantsGoodsWarehouseService.remove(Wrappers.lambdaQuery(MerchantsGoodsWarehouse.class).eq(MerchantsGoodsWarehouse::getGoodsCode, goodsCode));
            if (!remove){
                return new ResultUtil(ResultMapInfo.OPERATE_FAIL);
            }
        }
        List<JSONObject> jsonObjectList1 = new ArrayList<>();
        for (String str : conversion){
            String[] split = str.split("-");
            JSONObject jsonObject = new JSONObject();
            for (String str1 : split){
                GoodsSpecificationsCustom goodsSpecificationsCustom = map.get(map.get(str1).getLevelOfOne().toString());
                GoodsSpecificationsCustom goodsSpecificationsCustom1 = map.get(str1);
               jsonObject.put( goodsSpecificationsCustom.getSpecificationsName(),goodsSpecificationsCustom1.getSpecificationsName());
            }
            jsonObjectList1.add(jsonObject);
        }

        List<MerchantsGoodsWarehouse> list = new ArrayList<>();
        for (JSONObject jsonObject : jsonObjectList1){
            MerchantsGoodsWarehouse merchantsGoodsWarehouse = new MerchantsGoodsWarehouse();
            merchantsGoodsWarehouse.setSpecificationsCode(JSON.toJSONString(jsonObject));
            merchantsGoodsWarehouse.setSkuCode(TokenUtil.generateOrderNo());
            merchantsGoodsWarehouse.setSpecificationsJson(goodsSpecificationsService.formatJson(json,goodsCode,1));
            merchantsGoodsWarehouse.setGoodsCode(goodsCode);
            merchantsGoodsWarehouse.setMerchantsId(one.getMerchantsId());
            merchantsGoodsWarehouse.setName(one.getGoodsListTitle());
            merchantsGoodsWarehouse.setSalePrice(one.getGoodsPrice());
            merchantsGoodsWarehouse.setCostPrice(one.getGoodsPrice());
            merchantsGoodsWarehouse.setShowImage(one.getMainFigure());
            merchantsGoodsWarehouse.setTotalInventory(0);
            merchantsGoodsWarehouse.setBookInveentory(0);
            list.add(merchantsGoodsWarehouse);
        }
        boolean b = merchantsGoodsWarehouseService.saveBatch(list);
        if (!b){
            return new ResultUtil(ResultMapInfo.OPERATE_FAIL);
        }
        return new ResultUtil(ResultMapInfo.OPERATE_SUCCESS);
    }

    @Override
    public ResultUtil editMerchantsGoods(MerchantsGoods merchantsGoods) {
        boolean editState = merchantsGoodsService.updateById(merchantsGoods);
        return editState ?  new ResultUtil(ResultMapInfo.EDITSUCCESS) : new ResultUtil(ResultMapInfo.EDITFAIL);
    }
}
